/* pages/comment/comment.wxss */
const http = require("../../api/index")
// const util = require("../../utils/util")
const {
  baseURL
} = require("../../utils/request")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    oss_url: baseURL,
    score: "",
    content: "",
    fileList: [],
    campId: "",
    userId: "",
    releaseTime: "",
    imageUrl: "",
    anonymous: "1",
  },
  // 放弃编辑
  resetFiled() {
    this.setData({
      score: "",
      content: "",
      fileList: [],
      imageUrl: ""
    })
    //返回上一个页面
    wx.navigateBack({
      delta: 1
    });

  },
  // 上传完毕的回调函数
  afterRead(event) {
    wx.showLoading({
      title: '正在上传图片',
      mask: true
    })
    let that = this
    console.log(event, "图片上传event");
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式
    const userInfo = wx.getStorageSync('userInfo') || null;
    // console.log(userInfo,"######");
    const token = userInfo.token
    // 批量上传文件
    const uploadPromises = file.map((f) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'http://localhost:8080/common/upload', // 仅为示例，非真实的接口地址
          filePath: f.url,
          name: 'file',
          header: {
            'Authorization': `Bearer ${token}`,
            'content-type': 'application/json',
          },
          success: (res) => {
            try {
              // 尝试解析响应数据
              const parsedData = JSON.parse(res.data);
              resolve(parsedData);
            } catch (parseError) {
              console.error('解析响应数据失败:', parseError);
              reject(parseError);
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    });
    // 所有文件上传完成后更新 fileList 和 filenames 字符串
    Promise.all(uploadPromises).then((responses) => {
      const {
        fileList = []
      } = that.data;
      console.log(responses, "responses");
      // 确保 responses 是一个数组
      if (!Array.isArray(responses)) {
        throw new Error('responses is not an array');
      }
      const updatedFiles = responses.map((res, index) => ({
        url: res.url, // 上传后的文件 URL
      }));
      console.log(updatedFiles, "updatedFiles");
      // 更新 fileList
      fileList.push(...updatedFiles);
      that.setData({
        fileList
      });
      // 组合文件地址名
      const filenames = responses.map(res => res.fileName);
      const filenamesString = filenames.join(',');
      // 更新 filenamesString
      that.setData({
        imageUrl: filenamesString
      });
      console.log(that.data, "data");
      wx.hideLoading()

    }).catch((error) => {
      console.error('上传文件失败:', error);
    });
  },
  // 删除
  delete(e) {
    const index = e.detail.index
    this.setData({
      fileList: this.data.fileList.splice(1, index)
    })
  },
  //提交评价
  submitComment() {
    console.log(this.data, "data")
    http.addEvaluate(this.data).then(res => {
      console.log(res, 11111111)
      if (res.code == 200) {
        console.log(res)
        wx.showToast({
          title: '提交成功！',
          icon: "success",
        })
        setTimeout(() => {
          // 返回上一个页面
          wx.navigateBack({
            delta: 1
          });
        },1000)

      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    const userInfo = wx.getStorageSync("userInfo")
    this.setData({
      campId: options.campId,
      userId: userInfo.userId,
      releaseTime: formattedTime
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})